{extend name="app/shop/view/base.html"/}
{block name="resources"}
<style type="text/css">
.limit .layui-input{
	display: inline-block;
}
.limit .layui-form-mid{
	float: none;margin-right: 0
}
.limit .layui-form-radio{
	padding: 0;margin: 0;
}
.limit .layui-input[disabled]{
	background: #eee;cursor:not-allowed
}
.layui-form-item .layui-input-inline {
	width: 140px !important;
}
.len-mid {
	width: 440px !important;
}
.input-required {
	margin-bottom: 8px;
}
.member-detail {
	display: flex;
}
.checked-peo {
	width: 200px;
	border: 1px solid #ff700b;
	border-radius: 3px;
	padding: 12px 10px;
	margin: 10px 0;
}
.nickname {
	white-space: nowrap;
	overflow: hidden;
	text-overflow: ellipsis;
}
.title-wrap {
	font-size: 14px;
	font-weight: 600;
	color: #333;
	margin-left: 8px;
}
.title-wrap::before {
    content: "";
    display: inline-block;
    width: 3px;
    height: 14px;
    background-color: #FF6A00;
    position: absolute;
    left: 0;
    top: 29%;
    border-radius: 5px;
    transform: translateY(-50%);
}
.address-list {
	display: flex;
	flex-wrap: wrap;
	margin-top: 15px;
}
.good-box {
	width: 280px;
	padding: 10px;
	border: 1px solid #e8e8e8;
	margin:0 15px 15px 0;
	cursor: pointer;
}
.empty-goods .empty-text {
	line-height: 90px;
	margin-right: 20px;
}
.add-address {
	width: 105px;
	height: 102px;
	border: 1px solid #e8e8e8;
	display: flex;
	flex-direction: column;
	text-align: center;
	cursor: pointer;
	margin-bottom: 10px;
}
.add-address .span1 {
	margin-top: 20px;
    font-size: 35px;
    color: #949596;
}
.bargain-title {
	display: flex;
}
.title-icon {
	width: 60px;
	height: 60px;
	margin-right: 20px;
}
.title-icon img {
	width: 60px;
}
.title-right {
	width: 200px;
}
.title-name {
	width: 200px;
}
.layui-card-bottom .layui-form-label {
	width: 100px;
	line-height: 28px;
}
.good-name {
	margin-bottom: 5px;
}
.store-stock {
	margin-bottom: 5px;
}
.good-price {
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
	width: 260px;
}
.addclass {
	border: 1px solid #ff700b;
}

.new-footer {
	position: fixed;
	bottom: 0px;
	left: 180px;
	width: 89%;
	height: 50px;
}

.new-footer .layui-btn1 {
	position: absolute;
	bottom: 20px;
	left: 790px;
}
.new-footer .layui-btn2 {
	position: absolute;
	bottom: 20px;
	left: 870px;
}
.title-content {
	margin-right: 10px !important;
}
</style>
{/block}
{block name="main"}
<div class="member layui-card card-common card-brief">
	<div class="layui-card-header">
		<span class="card-title">正在为该会员下单</span>
	</div>
</div>

<div class="layui-card card-common card-brief">
	<div class="layui-card-header">
		<span class="card-title">会员信息</span>
	</div>

	<div class="layui-card-body">
		<div class="layui-form address-list"></div>
	</div>
</div>

<div class="layui-card card-common card-brief">
	<div class="layui-card-header">
		<span class="card-title">商品价格明细</span>
	</div>

	<div class="layui-card-body">
		<table id="attr_class_list" lay-filter="attr_class_list"></table>
	</div>

	<div class="layui-card-body">
		<div class="price_detailed"></div>
	</div>

</div>

<!-- 结算页面 -->
<script type="text/html" id="settle_page">
	<div class="form-wrap money">

		<div class="cash-settle layui-form">
			<div class="card-bottom">
				<div class="layui-card-bottom">
					<label class="layui-form-label">物流方式：</label>
					<div class="layui-input-inline" style="display: inline-block">
						<input type="radio" name="is_limit" value="1" title="快递配送" lay-filter="is_limit" checked>
					</div>

					<div class="layui-form-item">
						<label class="layui-form-label">使用余额：</label>
						<div class="layui-input-inline">
							<input type="radio" name="is_balance" value="1" title="是">
							<input type="radio" name="is_balance" value="0" title="否" checked>
						</div>
					</div>

					{if $is_use == 0}
					<span style="color:red">配送方式未开启</span>
					{/if}

					<input type="hidden" value="{$is_use}" id="is_use">

					<div class="layui-form-item">
						<label class="layui-form-label">运费：</label>
						<div class="layui-input-inline">
							<span>￥{{d.delivery_money}}</span>
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">商品金额：</label>
						<div class="layui-input-inline">
							<span>￥{{d.goods_money}}</span>
						</div>
					</div>
					<div class="layui-form-item">
						<label class="layui-form-label">运费：</label>
						<div class="layui-input-inline">
							<span>￥{{d.delivery_money}}</span>
						</div>
					</div>
					{{# if(d.promotion_money > 0){ }}
					<div class="layui-form-item">
						<label class="layui-form-label">优惠：</label>
						<div class="layui-input-inline">
							<span>￥{{d.promotion_money}}</span>
						</div>
					</div>
					{{# } }}
					<div class="layui-form-item">
						<label class="layui-form-label">合计：</label>
						<div class="layui-input-inline">
							<span>￥{{d.pay_money}}</span>
						</div>
					</div>
				</div>

			</div>
		</div>
	</div>
</script>

<input id="member_id" type="hidden" value="" />

<div class="layui-form form-wrap new-footer">
	<div class="form-row">
		<button class="layui-btn layui-btn1 layui-btn-primary" onclick="back()">返回</button>
		<button class="layui-btn layui-btn2 bg-color" lay-submit lay-filter="save_order">提交订单</button>
	</div>
</div>
{/block}
{block name="script"}
<script type="text/html" id="member_detail">
	<div class="layui-card-body">
		<div class="member-detail">
			<div class="table-title checked-peo border-color">
				<div class="title-pic">
					<img src="{{ns.img(d.headimg)}}" onerror=src="{:img('public/static/img/default_img/head.png')}" />
				</div>
				<div class="title-content">
					<div class="member-con-first">
						<h3 class="nickname">{{d.nickname}}</h3>
					</div>
					<div class="member-con-second">
						<p class="text-color-gray"><span class="member-mobile">{{d.mobile == "" ? '--' : d.mobile}}</span></p>
					</div>
				</div>
			</div>
		</div>
	</div>
</script>

<!-- 地址列表 -->
<script type="text/html" id="address_list">
	{{#  if (d.length == 0) {  }}
	<div class="empty-goods">
		<p class="empty-text">暂无地址</p>
	</div>
	{{#  } else {  }}
	{{#  layui.each(d, function(index, item) {  }}
	<div class="good-box  {{item.id == address_id ? 'addclass border-color' : ''}}" data-address-id="{{item.id}}" onclick="choiceAddress({{item.id}})">
		<div class="table-title">
			<div class="title-content">
				<p class="multi-line-hiding good-name" title="{{item.name}}">收货人：{{item.name}}</p>
				<div class="good-price">
					<p class="line-hideing store-stock" title="{{item.mobile}}">联系电话：{{item.mobile}}</p>
					<p class="basic-color good-price">联系地址：{{item.full_address}}{{item.address}}</p>
				</div>
			</div>
		</div>
	</div>
	{{#  })  }}
	{{#  }  }}
	<div class="add-address" onclick="addAddress()"><span class="span1">+</span><span>添加地址</span></div>
</script>

<script type="text/html" id="addAddress">

	<div class="layui-form form-wrap">
		<div class="layui-form-item">
			<label class="layui-form-label mid">收货人：</label>
			<div class="layui-input-block input-required">
				<input name="name" type="text" placeholder="请输入姓名" lay-verify="required" class="layui-input len-mid">
			</div>
			<label class="layui-form-label mid">联系电话：</label>
			<div class="layui-input-block input-required">
				<input name="mobile" type="text" placeholder="请输入联系电话" lay-verify="mobile" class="layui-input len-mid">
			</div>
			<div style="display: flex;">
				<label class="layui-form-label mid">地区：</label>

				<div class="layui-form-item" style="display: flex; margin-right: -20px;">
					<div class="layui-input-inline area-select">
						<select name="province_id" lay-filter="province_id" lay-verify="province_id">
							<option value="">请选择省份</option>
							{foreach $province_list as $k => $v}
							<option value="{$v.id}">{$v.name}</option>
							{/foreach}
						</select>
					</div>

					<div class="layui-input-inline area-select">
						<select name="city_id"  lay-filter="city_id" lay-verify="city_id">
							<option value="">请选择城市</option>
						</select>
					</div>

					<div class="layui-input-inline area-select">
						<select name="district_id"  lay-filter="district_id" lay-verify="district_id">
							<option value="">请选择区/县</option>
						</select>
					</div>
				</div>
			</div>

			<label class="layui-form-label mid">详细地址：</label>
			<div class="layui-input-block">
				<input name="address" type="text" placeholder="请输入收货人地址" lay-verify="required" class="layui-input len-mid">
			</div>
		</div>

		<div class="form-row mid">
			<button class="layui-btn member-search" lay-submit lay-filter="save" lay-submit>确定</button>
			<button class="layui-btn layui-btn-primary" onclick="closeAttrLayer()">返回</button>
		</div>
	</div>

</script>

<script type="text/javascript" src="SHOP_JS/address.js"></script>
<script>
	var buyer_info = {:json_encode($buyer_info, JSON_UNESCAPED_UNICODE)};
	var cart = JSON.parse('{:json_encode($cart, JSON_UNESCAPED_UNICODE)}');
	var address_id = JSON.parse('{:json_encode($address_id, JSON_UNESCAPED_UNICODE)}');
	var laytpl,add_attr_index = -1,repeat_flag,form,table;
	layui.use(['form', 'laytpl','laypage'], function() {
		laytpl = layui.laytpl;
		form = layui.form;
		repeat_flag = false;//防重复标识
		memberDetail(buyer_info);
		settleList();
		addressList();
		// syncData();

			form.render();

			table = new Table({
				data: cart,
				elem: '#attr_class_list',
				cols: [
					[{
						field: 'sku_name',
						title: '商品信息',
						unresize: 'false',
						width: '20%',
						templet: function (data) {
							var html = "";
							html += `<div class="bargain-title">
										<div class="title-icon">
											<img src="${ns.img(data.sku_image)}" alt="">
										</div>
										<div class="title-right">
										<p class="title-name multi-line-hiding">${data.sku_name}</p>
										<span>￥${data.sku_price}</span>
										</div>
									</div>`;
							return html;
						},
					}, {
						templet: function (data) {
							if (data.spec_name != '') {
								return data.spec_name
							} else {
								return '无'
							}
						},
						title: '商品规格',
						width: '10%'
					}, {
						unresize: 'false',
						title: '库存',
						field: 'stock',
						width: '10%'
					}, {
						unresize: 'false',
						title: '数量',
						width: '10%',
						field: 'num'
					}, {
						title: '成交价',
						width: '10%',
						unresize: 'false',
						templet: function (data) {
							return '￥' + (data.sku_price * data.num).toFixed(2);
						}
					}]
				]
			});

		/**
		 * 验证
		 */
		form.verify({
			required : function(value, item){
				var msg = $(item).attr("placeholder") != undefined ? $(item).attr("placeholder") : '';
				if(value == '') return msg;
			},
			mobile : function(value, item) {
				if(value == '') return '请输入手机号码';
				if (value != '') {
					if (!ns.parse_telephone(value) && !ns.parse_mobile(value)) {
						return '请输入正确的电话号码或手机号！';
					}
				}
			},
			province_id : function(value, item){
				if(value == ''){
					return '请选择省份';
				}
			},
			city_id : function(value, item){
				if(value == ''){
					return '请选择城市';
				}
			},
			district_id : function(value, item){
				if(value == ''){
					return '请选择区/县';
				}
			}
		});

		/**
		 * 监听新增地址提交
		 */
		form.on('submit(save)', function(data){

			if(repeat_flag) return;
			repeat_flag = true;

			var full_address  = [];
			full_address.push($("select[name=province_id] option:selected").text());
			full_address.push($("select[name=city_id] option:selected").text());
			full_address.push($("select[name=district_id] option:selected").text());

			data.field.full_address = full_address.join('-');

			$.ajax({
				type : "POST",
				dataType: 'JSON',
				url : ns.url("replacebuy://shop/replacebuy/addAddress"),
				async : true,
				data : data.field,
				success : function(res) {
					if (res.code == 0) {

						address_id = res.data;
						syncData();
						addressList();
						settleList();
						layer.msg('添加成功');

						layer.close(add_attr_index);

						setTimeout(function(){
							repeat_flag = false;
						},200)

					} else {
						layer.msg(res.message);
						repeat_flag = false;
					}
				}
			})
		});

		/**
		 * 监听订单提交
		 */
		form.on('submit(save_order)', function(data){

			if(address_id == '' || address_id == 0){
				layer.msg('请选择地址!');
				return;
			}
			var is_use = $("#is_use").val();
			if (is_use == 0){
				layer.msg('物流配送方式未开启!');
				return;
			}

			if(repeat_flag) return;
			repeat_flag = true;

			var is_balance = $("input[name='is_balance']:checked").val();

			$.ajax({
				type : "POST",
				dataType: 'JSON',
				url : ns.url("replacebuy://shop/ordercreate/create"),
				async : true,
				data : {"cart": JSON.stringify(cart), "is_balance" : is_balance},
				success : function(res) {
					repeat_flag = false;

					if (res.code == 0) {
						cart = [];
						address_id = 0;
						syncData();
						syncCart();
						syncUser();
						layer.msg('提交成功！');
						location.href = ns.url("replacebuy://shop/replacebuy/index");
					} else {
						layer.msg(res.message);
					}
				}
			})
		});
	});

	// 选中地址
	function choiceAddress(id) {
		$(`.good-box[data-address-id=${id}]`).addClass('addclass border-color').siblings().removeClass('addclass border-color');
		address_id = id;
		syncData();
		settleList();
	}

	// 会员详情页面渲染
	function memberDetail(data) {
		laytpl($("#member_detail").html()).render(data, function(html) {
			$(".member").append(html);
			$("#member_id").val(data.member_id);
		})
	}

	// 同步购物车数据
	function syncCart() {
		$.ajax({
			url: ns.url("replacebuy://shop/replacebuy/cart"),
			type: "POST",
			dataType: "JSON",
			async: false,
			data: {"cart_json": JSON.stringify(cart)}
		})
	}

	//注销会员
	function syncUser() {
		$.ajax({
			url: ns.url("replacebuy://shop/replacebuy/logoutBuyer"),
			type: "POST",
			dataType: "JSON",
			async: false
		})
	}

	// 结算
	function settleList() {
		$.ajax({
			url: ns.url("replacebuy://shop/ordercreate/payment"),
			type: "POST",
			dataType: "JSON",
			async: false,
			data: {"cart": JSON.stringify(cart)},
			success: function(res) {
				if (res.code == 0) {

					var data = res.data;
					laytpl($("#settle_page").html()).render(data, function(html) {
						$(".price_detailed").html(html);
					});
					form.render();

				} else {
					layer.msg(res.message);
				}
			}
		})
	}

	// 地址列表渲染
	function addressList() {
		$.ajax({
			url: ns.url("replacebuy://shop/replacebuy/addressPage"),
			async: false,
			type: "POST",
			dataType: "JSON",
			data:{type: 1},
			success: function(res) {
				if (res.code == 0) {
					var data = res.data;
					laytpl($("#address_list").html()).render(data, function(html) {
						$(".address-list").html(html);
					});
				} else {
					layer.msg(res.message);
				}
			}
		});
	}


	//新增地址
	function addAddress(){
		var add_attr = $("#addAddress").html();
		laytpl(add_attr).render({}, function(html) {
			add_attr_index = layer.open({
				title: '添加收货地址',
				skin: 'layer-tips-class',
				type: 1,
				area: ['650px', '350px'],
				content: html,
				success: function (){
					form.render();
				}
			});

		});

		$(document).keydown(function (event) {
			if (event.keyCode == 13) {
				$(".member-search").trigger("click");
			}
		});
	}

	// 同步数据
	function syncData() {
		$.ajax({
			url: ns.url("replacebuy://shop/replacebuy/choiceAddress"),
			type: "POST",
			dataType: "JSON",
			async: false,
			data: {"address_id": address_id}
		})
	}

	function back() {
		location.href = ns.url("replacebuy://shop/replacebuy/index");
	}
	function closeAttrLayer() {
		layer.close(add_attr_index);
	}
</script>
{/block}